<template>
  <div class="app-container">
    <div class="main">
      <div class="filter-container g-bgc-fill-el-input">
        <div class="filter-left">
          <el-select v-model="listQuery.packetType" placeholder="包类型" clearable @change="comHandleFilterSelectChange"
            style="width: 122px" class="filter-item">
            <el-option v-for="(item, index) in packetTypeOptions" :key="index" :label="item.label" :value="item.id" />
          </el-select>
          <!-- 这一期不弄 -->
          <!-- <el-select v-model="listQuery.createBy" placeholder="创建人" clearable @change="comHandleFilterSelectChange"
            style="width: 122px" class="filter-item">
            <el-option v-for="(item, index) in packetTypeOptions" :key="'br' + index" :label="item.menufacturer"
            :value="item.id" />
          </el-select> -->
          <el-date-picker v-model="listQuery.date" type="daterange" @change="comHandleFilterDateChange"
            format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss" style="width: 208px" range-separator=""
            start-placeholder="开始时间" end-placeholder="结束时间">
          </el-date-picker>
          <np-input-search v-model="listQuery.keyword" placeholder="搜索资源包、版本号" style="width: 360px;"
            @all-search="comHandleFilterAllSearch" />
        </div>
        <div class="filter-right">
          <el-button type="warning" @click="handleNewAddResBundle">新增资源包</el-button>
        </div>
      </div>

      <el-table class="g-el-table" :data="list" v-loading="listLoading">
        <el-table-column label="资源包" prop="title" width="200PX">
          <div slot-scope="{row}">
            {{ row.upgradeName }}
          </div>
        </el-table-column>
        <el-table-column label="版本号" width="120px">
          <template slot-scope="{row}">
            <span>{{ row.targetVersion }}</span>
          </template>
        </el-table-column>
        <el-table-column label="包类型" width="120px">
          <template slot-scope="{row}">
            <span>{{ row.packetType | packetTypeFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人" width="120px">
          <template slot-scope="{row}">
            <span>{{ row.createBy }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="150px">
          <template slot-scope="{row}">
            <span>{{ row.createDate }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="230" fixed="right" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button type="text" @click="handleEdit(row)" :disabled="row.delete_loading">编辑</el-button>
            <el-button type="text" @click="handleDownload(row)">下载</el-button>
            <el-button type="text" @click="handleDel(row)" :loading="row.delete_loading">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <np-pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
        @pagination="getList" />
    </div>

    <ListEditAddUpgradeDialog :visible.sync="dialogEditAddProblemVisible" :info-row="editAddInfoRow"
      :packet-type-options="packetTypeOptions" @editAddSuccessChange="editAddSuccessChange" />
  </div>
</template>

<script>
import { fetchList, deleteUpgradeInfo, } from '@/api/ota-upgrade-management/list'
import ListEditAddUpgradeDialog from "./components/ListEditAddUpgradeDialog.vue"
import { downloadFile } from '@/api/public'
import { exportFile } from '@/utils'

const packetTypeOptions = [{
  id: 1,
  label: '相册 APK',
}, {
  id: 2,
  label: 'Linux APK',
}]

export default {
  name: 'ComplexTable',
  components: { ListEditAddUpgradeDialog },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,

        packetType: undefined,
        createBy: undefined,
        keyword: undefined,

        date: '',
        startDate: undefined,
        endDate: undefined,
      },
      // 包的类型，1 P6AI相册app，2 Linux虚拟app，3 其他
      packetTypeOptions,

      // 编辑添加问题弹窗参数
      editAddInfoRow: null,
      dialogEditAddProblemVisible: false,
    }
  },
  filters: {
    packetTypeFilter(type) {
      let v = packetTypeOptions.find(el => type === el.id)
      if (v) {
        return v.label
      }
      return ''
    }
  },
  computed: {
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      let pans = { ...this.listQuery }
      delete pans.date
      fetchList(this.listQuery).then(res => {
        if (res.code === 200) {
          this.list = (res.data.list || []).map(el => {
            el.disable_loading = false
            el.delete_loading = false
            return el
          })
          this.total = res.data.total
        }

        // Just to simulate the time of the request
        this.listLoading = false
      }).catch(err => {
        this.listLoading = false
      })
    },
    comHandleFilterAllSearch(e) {
      this.listQuery.pageNum = 1
      this.getList()
    },
    comHandleFilterSelectChange(e) {
      this.listQuery.pageNum = 1
      this.getList()
    },
    comHandleFilterDateChange(e) {
      this.listQuery.pageNum = 1
      this.listQuery.startDate = e ? e[0] : ''
      this.listQuery.endDate = e ? e[1] : ''
      this.getList()
    },
    editAddSuccessChange(e) {
      // e 判断是编辑 edit 还是添加 add
      if (e === 'add') {
        this.getList()
        return
      }
      if (e === 'edit') {
        this.getList()
      }
    },
    handleNewAddResBundle() {
      this.editAddInfoRow = null
      this.dialogEditAddProblemVisible = true
    },
    handleEdit(row) {
      this.editAddInfoRow = row
      this.dialogEditAddProblemVisible = true
    },
    handleDownload(row) {
      let url = row.packageUrl
      if (!url) {
        this.$message.error('此条数据包路径不存在，无法下载。')
        return
      }
      let name = '';
      try {
        let arr = row.packageUrl.split('/');
        name = arr[arr.length - 1]
      } catch (error) { }
      if (!name) {
        this.$message.error('此条数据包名字不存在，无法下载。')
      }
      downloadFile(url).then(res => {
        let fileName = name;
        exportFile(res, fileName);
      }).catch(err => { })
    },
    handleDel(row) {
      if (row.delete_loading) {
        return
      }
      this.$confirm('确认删除此资源包？请谨慎操作！')
        .then(_ => {
          row.delete_loading = true
          let params = {
            id: row.id || '',
            path: row.filePath || '',
          }
          deleteUpgradeInfo(params).then(res => {
            if (res.code === 200) {
              this.$message.success('删除成功!')
              this.listQuery.pageNum = 1
              this.getList()
            } else {
              this.$message.error('删除失败。')
            }
            row.delete_loading = false
          }).catch(err => {
            this.$message.error('系统错误，服务失败。')
            row.delete_loading = false
          })
        })
        .catch(_ => { });
    },
  }
}
</script>
<style scoped lang="scss">
.app-container {
  height: 100%;
  overflow: auto;
}

.main {
  background-color: #fff;
  border-radius: 16px;
  padding: 20px 20px 28px;
}
</style>